package org.javaforever.gatescore.verb;

import java.util.ArrayList;
import java.util.List;

import org.javaforever.gatescore.core.FrontCodeBlock;
import org.javaforever.gatescore.core.FrontDomain;
import org.javaforever.gatescore.core.FrontMethod;
import org.javaforever.gatescore.core.FrontVerb;
import org.javaforever.gatescore.core.Statement;
import org.javaforever.gatescore.core.Writeable;
import org.javaforever.gatescore.core.WriteableUtil;
import org.javaforever.gatescore.utils.StringUtil;

public class Update extends FrontVerb{
	private static final long serialVersionUID = -5607577902722557859L;
	
	public Update(FrontDomain d) {
		super(d);		
		this.setVerbName("Update"+d.getCapFirstDomainName());
	}

	@Override
	public FrontMethod generateControllerMethod() throws Exception {
		FrontMethod method = new FrontMethod();
		method.setStandardName("update"+StringUtil.capFirst(this.domain.getStandardName()));
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,0,"update"+this.domain.getCapFirstDomainName()+"(){"));
		sList.add(new Statement(2000L,1,"var data = this.form;"));
		sList.add(new Statement(2500L,1,"Object.keys(data).forEach(key => data[key]=isBlank(data[key])?'':data[key]);"));
		sList.add(new Statement(3000L,1,"update"+this.domain.getCapFirstDomainName()+"(data).then(response => {"));
		sList.add(new Statement(4000L,2,"this.reload();"));
		sList.add(new Statement(5000L,1,"});"));
		sList.add(new Statement(6000L,1,"},"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}

	@Override
	public FrontMethod generateApiMethod() throws Exception {
		FrontMethod method = new FrontMethod();
		method.setStandardName("update"+StringUtil.capFirst(this.domain.getStandardName()));
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,0,"export function update"+this.domain.getCapFirstDomainName()+"(data) {"));
		sList.add(new Statement(2000L,0,"return request({"));
		sList.add(new Statement(3000L,1,"url: '"+this.domain.getLowerFirstDomainName()+"Facade/update"+this.domain.getCapFirstDomainName()+"',"));
		sList.add(new Statement(4000L,1,"method: 'post',"));
		sList.add(new Statement(5000L,1,"data"));
		sList.add(new Statement(6000L,0,"})"));
		sList.add(new Statement(7000L,0,"}"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}

	@Override
	public FrontCodeBlock generateRouteBlockBlock() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
